/*
 * @Author: your name
 * @Date: 2021-04-07 10:25:58
 * @LastEditTime: 2021-04-14 15:12:37
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \web\node\route\user.js
 */ 
import express, { Router } from "express";
const router = express.Router({});

import User from "./../models/User";
import config from "./../src/config";
import md5 from "blueimp-md5";
import formidable from "formidable";
import { basename } from "path";


const S_KEY = "@^xrt%sf?q~xv24XdCIE"

 
/*****************************用户中心接口API-start****************************/

/* 添加管理人员的接口 */   
router.post("/user/api/add", (req, res, next) => {
  const user_name = req.body.user_name || "";
  const user_pwd = md5(req.body.user_pwd + S_KEY) || "";

  const user = new User({
      //用户名
      user_name: user_name,
      //用户密码
      user_pwd: user_pwd
  })

  user.save((err,result)=>{
      if(err){
          return next(err)
      }
      res.json({
          status:200,
          message:"用户创建成功！"
      })
  })

});
  
/* 登录接口 */ 
router.post("/user/api/login",(req,res,next)=>{
    let user_name = req.body.user_name;
    let user_pwd = req.body.user_pwd;

    User.findOne({user_name:user_name},(err,user)=>{
        if(err){
            return next(err)
        }
        if(user){
            if(user.user_pwd === user_pwd){
                //数据库中存储session
                req.session.token = user._id;
                
                res.json({
                    status:200,
                    result:{
                        token:user._id, 
                        message:"登录成功！"
                    }
                })
            }else{
                res.json({
                    status:-1,
                    result:{
                        message:"密码输入错误！"
                    }
                })
            }
        }else{
            res.json({
                status:-1,
                result:{
                    message:"用户不存在！"
                }
            })
        }
    })
})
 
/* 退出登录接口 */
router.get("/back/user/api/logout",(req,res,next)=>{
    //销毁session
    req.session.destroy()

    res.json({
        status:200,
        message:"退出登录成功！"
    })
})

/* 请求用户数据--部分 */
router.get("/back/user/aip/u_msg/:token", (req, res, next) => {
    User.find(
        { _id: req.params.token },
        "-_id icon_url real_name  intro_self points rank gold phone e_mail intro_self",
        (err, user) => {
          if (err) {
            return next(err);
          }
          res.json({
            status: 200,
            result: user,
          });
        }
      );
  });

/* 请求用户数据--所有 */
router.get("/back/user/aip/u_msg_all/:token", (req, res, next) => {
    User.find(
        { _id: req.params.token },
        "-_id -user_name -user_pwd -l_edit -c_time",
        (err, user) => {
          if (err) {
            return next(err);
          }
          res.json({
            status: 200,
            result: user,
          });
        }
      );
  });
  
/* 根据id去修改用户数据 */
router.post("/back/user/api/edit", (req, res, next) => {

    const form = new formidable.IncomingForm();
    form.uploadDir = config.uploadsPath;
    form.keepExtensions = true;
    form.parse(req, (err, fields, files) => {
      if (err) {
        return next(err);
      }
      let body = fields;

  
      User.findById(body.token,(err,user)=>{
   
        // 用户名称
        user.real_name = body.real_name,
        // 头像地址
        user.icon_url = body.icon_url || basename(files.icon_url.path),
        // 手机号码
        user.phone = body.phone,
        // e_mail
        user.e_mail = body.e_mail,
        // 自我介绍
        user.intro_self = body.intro_self
  
    
        user.save((err, result) => {
          if (err) {
            return next(err);
          }
          res.json({
            status: 200,
            result: "用户信息修改成功！",
          });
        });
      })
      
    });
  });

/* 根据id去修改用户密码 */
router.post("/back/user/api/change_pwd",(req, res, next) => {
  let body = req.body;
  let token = body.token, old_pwd = body.old_pwd, new_pwd = body.new_pwd;

  User.findById(token,(err,user)=>{
    if(err){
      next(err);
    }
    
    if(user){
      //对比密码
      if(user.user_pwd === old_pwd){
        user.user_pwd = new_pwd;
        user.save((err,result)=>{
          if(err){
            next (err)
          }
          if(result){
            res.json({
              satatus: 200,
              message:"密码更改成功！"
            })
          }
        })
      }else{
        res.json({
          satatus:-1,
          message:"密码输入错误！"
        })
      }
    }else{
      res.json({
        satatus:-1,
        message:"没有找到该用户！"
      })
    }
  })
})


/*****************************用户中心接口API-end****************************/

 

 
/*****************************用户界面-start****************************/
router.get("/back/login", (req, res, next) => {
  res.render("back/login.html");
});

router.get("/back/u_center", (req, res, next) => {
  res.render("back/user_center.html");
});

router.get("/back/u_set", (req, res, next) => {
  res.render("back/user_message.html");
});

router.get("/back/u_reset_pwd", (req, res, next) => {
  res.render("back/reset_pwd.html");
});
/*****************************用户界面-end****************************/

export default router;
